package com.fulihui.systemcore.repository.impl;

import com.fulihui.systemcore.dal.convertor.ApiTemplateConv;
import com.fulihui.systemcore.dal.dataobj.ApiTemplate;
import com.fulihui.systemcore.dal.dataobj.ApiTemplateExample;
import com.fulihui.systemcore.dal.mapper.ApiTemplateMapper;
import com.fulihui.systemcore.dto.ApiTemplateDTO;
import com.fulihui.systemcore.repository.ApiTemplateRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * Created by  lz on 2017-5-31.
 */
@Repository
public class ApiTemplateRepositoryImpl implements ApiTemplateRepository {
    @Autowired
    private ApiTemplateMapper apiTemplateMapper;

    /**
     * Create.
     *
     * @param templateDTO the template dto
     */
    @Override
    public Long create(ApiTemplateDTO templateDTO) {
        ApiTemplate record = new ApiTemplate();
        BeanUtils.copyProperties(templateDTO, record);
        apiTemplateMapper.insertSelective(record);
        return record.getId();
    }

    /**
     * 根据apiCode 查询
     *
     * @param apiCode the api code
     * @return the api template dto
     */
    @Override
    public ApiTemplateDTO queryByApiCode(String apiCode) {
        ApiTemplateExample example = new ApiTemplateExample();
        example.createCriteria().andApiCodeEqualTo(apiCode);
        List<ApiTemplate> apiTemplates = apiTemplateMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(apiTemplates)) {
            return null;
        }
        ApiTemplate apiTemplate = apiTemplates.get(0);
        return ApiTemplateConv.convert2DTO(apiTemplate);
    }

    /**
     * Query by pk api template dto.
     *
     * @param id the id
     * @return the api template dto
     */
    @Override
    public ApiTemplateDTO queryByPk(Long id) {
        ApiTemplate apiTemplate = apiTemplateMapper.selectByPrimaryKey(id);
        return ApiTemplateConv.convert2DTO(apiTemplate);
    }

    /**
     * Query page list.
     *
     * @param page the page
     * @param rows the rows
     * @return the list
     */
    @Override
    public List<ApiTemplateDTO> queryPage(int page, int rows) {
        ApiTemplateExample example = new ApiTemplateExample();
        int offset = (page - 1) * rows;
        example.setOffset(offset);
        example.setLimit(rows);
        example.setOrderByClause("id desc");
        List<ApiTemplate> apiTemplates = apiTemplateMapper.selectByExample(example);
        return ApiTemplateConv.convert2List(apiTemplates);
    }

    @Override
    public int count() {
        ApiTemplateExample example = new ApiTemplateExample();
        return (int) apiTemplateMapper.countByExample(example);
    }
}
